package com.example.seh.add.errands;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.example.seh.R;
import com.example.seh.add.idle.AddIdleActivity;
import com.example.seh.add.post.AddPostActivity;
import com.example.seh.constant.Constant;
import com.example.seh.databinding.ActivityAddErrandsBinding;
import com.example.seh.util.BackUtil;
import com.example.seh.util.JudgeContent;
import com.example.seh.util.UserMsg;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddErrandsActivity extends AppCompatActivity {

    private ActivityAddErrandsBinding addErrandsBinding;
    private AlertDialog dialog;
    private int hour,minute;
    private String time1,time2,dateStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }

        addErrandsBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_errands);
        initEvent();
    }

    /**
     * Initial Event
     */
    private void initEvent() {
        /**
         * 点击上方返回键
         */
        addErrandsBinding.idleBack3.setOnClickListener(v -> {
            BackUtil.JumpBack(AddErrandsActivity.this);

        });

        /**
         * 点击发布按钮
         */
        addErrandsBinding.btnPublish3.setOnClickListener(v -> {
            if (Judge()){
                AlertDialog.Builder dialog = new AlertDialog.Builder(AddErrandsActivity.this);
                dialog.setTitle("提示")
                        .setMessage("确定要发布吗")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                String code = addErrandsBinding.idleCode.getText().toString();
                                String content = addErrandsBinding.idleContent3.getText().toString();
                                String home_address = addErrandsBinding.goodsAddress2.getText().toString();
                                String goods_address = addErrandsBinding.goodsAddress3.getText().toString();
                                String contents = code+content+home_address+goods_address;

                                JudgeContent.setData(contents, new JudgeContent.DataCallback() {
                                    @Override
                                    public void onFailure() {
                                        Log.e("fail","发送失败");
                                    }

                                    @Override
                                    public void onResponse(String data) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(data);
                                            JSONArray wordList = jsonObject.getJSONArray("word_list");

                                            if (wordList.length() == 0) {
                                                sendData();
                                                BackUtil.Back(AddErrandsActivity.this);
                                                finish();
                                            } else {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(AddErrandsActivity.this,"发布内容包含敏感词汇，请修改后发布",Toast.LENGTH_LONG).show();
                                                    }
                                                });
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });


                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                dialog.create().show();
            }

        });



        /**
         * 点击送达时间
         */
        addErrandsBinding.errandsTime.setOnClickListener(v -> {
            dialog = new AlertDialog.Builder(AddErrandsActivity.this).create();
            dialog.show();
            dialog.getWindow().setContentView(R.layout.time_dialog);
            dialog.getWindow().setBackgroundDrawableResource(R.drawable.time_dialog_bg);

            Calendar calendar = Calendar.getInstance();
            hour = calendar.get(Calendar.HOUR);
            minute = calendar.get(Calendar.MINUTE);
            ((TimePicker) dialog.getWindow().findViewById(R.id.time_picker)).setIs24HourView(true);
            ((TimePicker) dialog.getWindow().findViewById(R.id.time_picker)).setOnTimeChangedListener(new TimePicker.OnTimeChangedListener()
            {
                public void onTimeChanged(TimePicker view, int hourOfDay, int minute)
                {
                    AddErrandsActivity.this.hour = hourOfDay;
                    AddErrandsActivity.this.minute = minute;
                    time1=Integer.toString(AddErrandsActivity.this.hour);
                    time2=Integer.toString(AddErrandsActivity.this.minute);
                    if (Integer.parseInt(time1)<10){
                        time1 = "0"+time1;
                    }
                    if (Integer.parseInt(time2)<10){
                        time2 = "0"+time2;
                    }
                    dateStr=time1+" ："+time2;
                }
            });
            dialog.getWindow().findViewById(R.id.time_sure).setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    SimpleDateFormat df = new SimpleDateFormat("HH:mm");
                    try {
                        df.parse(time1+" : "+time2);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    addErrandsBinding.errandsTime.setText(dateStr);
                    dialog.dismiss();
                }});
        });

    }

    private boolean Judge() {
        String content = addErrandsBinding.idleContent3.getText().toString().trim();
        String code = addErrandsBinding.idleCode.getText().toString().trim();
        String homeAddress = addErrandsBinding.goodsAddress2.getText().toString().trim();
        String goodsAddress = addErrandsBinding.goodsAddress3.getText().toString().trim();
        String time = addErrandsBinding.errandsTime.getText().toString().trim();
        String money = addErrandsBinding.goodsMoney2.getText().toString().trim();

        if (content.isEmpty()) {
            Toast.makeText(this, "请输入代取需求", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (code.isEmpty()) {
            Toast.makeText(this, "请输入取件码", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (homeAddress.isEmpty()) {
            Toast.makeText(this, "请输入收件地址", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (goodsAddress.isEmpty()) {
            Toast.makeText(this, "请输入宝贝所在地", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (time.isEmpty()) {
            Toast.makeText(this, "请输入送达时间", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (money.isEmpty()) {
            Toast.makeText(this, "请输入合适价格", Toast.LENGTH_SHORT).show();
            return false;
        }


        return true;
    }

    /**
     * 发送数据
     */
    private void sendData() {
        String  authorId = "3";
        String code = addErrandsBinding.idleCode.getText().toString();
        String content = addErrandsBinding.idleContent3.getText().toString();
        //String addressee = addErrandsBinding.addressee.getText().toString();
        String home_address = addErrandsBinding.goodsAddress2.getText().toString();
        String goods_address = addErrandsBinding.goodsAddress3.getText().toString();
        // 获取当前日期
        Date currentDate = new Date();
        // 创建日期格式化对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 格式化日期
        String formattedDate = dateFormat.format(currentDate);
        String time = formattedDate + addErrandsBinding.errandsTime.getText().toString();
        String price = addErrandsBinding.goodsMoney2.getText().toString();
//
        JSONObject object = new JSONObject();
        try {
            object.put("deliverDesc",content);
            object.put("deliverCode",code);
            object.put("receiveName",home_address);
            object.put("addressName",goods_address);
            object.put("confirmTime",time);
            object.put("deliverPrice",price);
            object.put("issuerId", UserMsg.userDTO.getUserId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody2 = RequestBody.create(type,""+object.toString());

        Request request = new Request.Builder()
                .url(Constant.ADD_ERRANDS)
                .post(requestBody2)
                .build();

        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("OkHttp","发送失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("OkHttp","发送成功");
            }
        });

    }

    /**
     *
     * 如果用户点了返回键
     * @param keyCode
     * @param event
     * @return
     */

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            BackUtil.JumpBack(AddErrandsActivity.this);

        }
        return false;
    }
}